package com.sugon.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.sugon.consts.ErmsCodePrefix;
import com.sugon.dao.ModuleArchivesDao;
import com.sugon.dao.ModuleRepairRocordDao;
import com.sugon.entity.ModuleArchivesEntity;
import com.sugon.entity.ModuleRepairRocordEntity;
import com.sugon.entity.dto.MoldRepairTicketExportParam;
import com.sugon.modules.mold.consts.MoldReplacePartProgress;
import com.sugon.service.ModuleRepairRocordService;
import com.sugon.service.SysProcessInfoService;
import com.sugon.utils.Constant;
import com.sugon.utils.DateUtil;
import com.sugon.utils.ProcessInfoEnum;
import com.sugon.utils.excel.ExcelExport;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * 模具报修记录Service实现类
 *
 * @author sugon
 * @date 2019-08-15 09:07:09
 */
@Service("moduleRepairRocordService")
public class ModuleRepairRocordServiceImpl implements ModuleRepairRocordService {

    @Autowired
    private ModuleRepairRocordDao moduleRepairRocordDao;
    @Autowired
    private SysProcessInfoService sysProcessInfoService;
    @Autowired
    private ModuleArchivesDao moduleArchivesDao;

    @Override
    public ModuleRepairRocordEntity queryObject(String id) {
        return moduleRepairRocordDao.queryObject(id);
    }

    @Override
    public ModuleRepairRocordEntity queryByCode(String repairCode) {
        Map<String, Object> queryParam = MapUtil.newHashMap(1);
        queryParam.put("repairCode", repairCode);
        List<ModuleRepairRocordEntity> moduleRepairRocordList = queryList(queryParam);
        return CollectionUtil.isNotEmpty(moduleRepairRocordList) ? moduleRepairRocordList.get(0) : null;
    }

    @Override
    public List<ModuleRepairRocordEntity> queryList(Map<String, Object> map) {
        return moduleRepairRocordDao.queryList(map);
    }

    @Override
    public int queryTotal(Map<String, Object> map) {
        return moduleRepairRocordDao.queryTotal(map);
    }

    @Override
    public int save(ModuleRepairRocordEntity moduleRepairRocord) {
        moduleRepairRocord.setId(RandomUtil.randomString(32));
        if (StrUtil.isEmpty(moduleRepairRocord.getRepairCode())) {
            //获取维修编码
            moduleRepairRocord.setRepairCode(generateUniqueCode());
        }
        moduleRepairRocord.setCreateDate(cn.hutool.core.date.DateUtil.date());
        moduleRepairRocord.setDelFlag(Constant.IS_NOT_DEL_INT);
        moduleRepairRocord.setProgress(MoldReplacePartProgress.NEW);
        return moduleRepairRocordDao.save(moduleRepairRocord);
    }

    @Override
    public String generateUniqueCode() {
        String repairTicketCodePrefix = ErmsCodePrefix.MOLD_REPAIR_TICKET_CODE_PREFIX + com.sugon.modules.utils.DateUtil.today() + "-";
        String lastestRepairTicketCode = moduleRepairRocordDao.getLastestRepairTicketCode(repairTicketCodePrefix);
        if (StrUtil.isEmpty(lastestRepairTicketCode)) {
            return repairTicketCodePrefix + "0001";
        } else {
            return com.sugon.modules.utils.StrUtil.increase(lastestRepairTicketCode, repairTicketCodePrefix, 4, 1);
        }
    }

    @Override
    public int update(ModuleRepairRocordEntity moduleRepairRocord) {
        moduleRepairRocord.setUpdateDate(DateUtil.now());
        return moduleRepairRocordDao.update(moduleRepairRocord);
    }

    @Override
    public int delete(String id) {
        return moduleRepairRocordDao.delete(id);
    }

    @Override
    public int deleteBatch(String[] ids) {
        return moduleRepairRocordDao.deleteBatch(ids);
    }

    @Override
    public int updateStatus(String id) {

        //更新模具状态
        ModuleRepairRocordEntity repairRocordEntity = moduleRepairRocordDao.queryObject2(id);
        //自动更新模具状态
        String moduleCode = repairRocordEntity.getModuleNo();
        ModuleArchivesEntity mae = moduleArchivesDao.queryObjectByCode(moduleCode);
        mae.setCurrentState(1);//设置为维护中
        moduleArchivesDao.update(mae);

        return moduleRepairRocordDao.updateStatus(id);
    }

    /**
     * 执行
     *
     * @return
     */
    @Override
    public int doRepair(ModuleRepairRocordEntity moduleRepairRocord) {
        String id = moduleRepairRocord.getId();
        ModuleRepairRocordEntity mre = moduleRepairRocordDao.queryObject2(id);
        mre.setFaultType(moduleRepairRocord.getFaultType());
        mre.setDealMethod(moduleRepairRocord.getDealMethod());
        return moduleRepairRocordDao.update(mre);
    }

    @Override
    public List<MoldRepairTicketExportParam> prepareExportData(Map<String, Object> params) {
        List<MoldRepairTicketExportParam> exportDataList = moduleRepairRocordDao.prepareExportData(params);
        return Optional.ofNullable(exportDataList).orElse(CollectionUtil.newArrayList());
    }

    @Override
    public void export(Map<String, Object> params, HttpServletResponse response) {
        List<ModuleRepairRocordEntity> recordList = moduleRepairRocordDao.queryList(params);
        ExcelExport ee = new ExcelExport("模具维修记录");
        // No.	分类	异常停止描述（维修记录）	日期	班次	开始时间	结束时间	停止时间	机台	模具	故障级别
        String[] header = new String[]{"No.", "分类", "异常停止描述", "日期", "班次", "开始时间", "结束时间", "停止时间", "机台", "模具", "故障级别"};
        List<Map<String, Object>> list = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(recordList)) {
            ModuleRepairRocordEntity mrr;
            for (int i = 0; i < recordList.size(); i++) {
                mrr = recordList.get(i);
                LinkedHashMap<String, Object> map = new LinkedHashMap<>();
                map.put("no", i + 1);
                // 故障类型
                map.put("faultTypeName", mrr.getFaultTypeName());
                // 异常停止描述
                map.put("recordDesc", mrr.getRecordDescr());
                // 停机日期 TODO
                if (mrr.getOrderExecuteDate() != null) {
                    map.put("date", cn.hutool.core.date.DateUtil.formatDate(mrr.getOrderExecuteDate()));
                }
                // 班次
                map.put("work", " - ");
                //  开始时间
                if (mrr.getOrderExecuteDate() != null) {
                    map.put("orderExecuteDate", cn.hutool.core.date.DateUtil.formatDateTime(mrr.getOrderExecuteDate()));
                }
                //  结束时间
                if (mrr.getOrderEndDate() != null) {
                    map.put("orderEndDate", cn.hutool.core.date.DateUtil.formatDateTime(mrr.getOrderEndDate()));
                }
                //  停止时间
                map.put("repairDuration", mrr.getRepairDuration());
                //  机台
                map.put("devName", mrr.getDevName());
                //  模具
                map.put("moduleNo", mrr.getModuleNum());
                //  故障级别
                map.put("faultLevel", " - ");
                list.add(map);
            }
            ee.addSheetByMap("故障停机报表", list, header);
            ee.export(response);
        }
    }

    @Override
    public int endErrorApi(String id, String userId, String deptId) {
        ModuleRepairRocordEntity moduleRepairRocord = moduleRepairRocordDao.queryObject2(id);
        moduleRepairRocord.setId(id);
        moduleRepairRocord.setUpdateDate(new Date());
        moduleRepairRocord.setOrderExecuteUser(userId);
        moduleRepairRocord.setCreateDate(new Date());
        moduleRepairRocord.setStatus(0);
        moduleRepairRocord.setDelFlag(1);
        moduleRepairRocordDao.update(moduleRepairRocord);
        //添加流程记录
        return sysProcessInfoService.saveProcessInfoApi2(id, ProcessInfoEnum.MDE_YJWH, 1, "", "模具维修-流程结束", userId, deptId);
    }

}
